package com.example.demo.practice.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by hanbo on 2018-01-11.
 */

public class GradientRoundSquare extends View{
    private Paint paint;
    public GradientRoundSquare(Context context) {
        super(context);
        paint=new Paint();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public GradientRoundSquare(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint=new Paint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float width = getWidth();
        float height = getHeight();
        paint.setColor( StringToColor("#4ef1ff"));
        paint.setStrokeWidth(4);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        RectF rectF = new RectF(0, 0, width, height);
        canvas.drawRoundRect(rectF,10,10,paint);
        super.onDraw(canvas);
    }
    /**
     * #颜色转16进制颜色
     *
     * @param str {String} 颜色
     * @return
     */
    private int StringToColor(String str) {
        return Color.parseColor(str);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            paint.setShader(new LinearGradient(
                    0, 0, getWidth(), 0,
                    StringToColor("#4ef1ff"), StringToColor("#0e9aeb"),
                    Shader.TileMode.CLAMP));
        }
    }
}
